package com.earthea.scaffold.common.util;

import com.earthea.scaffold.domain.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 安全服务工具类
 */
public class SecurityUtils {

    /**
     * 获取用户
     */
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            return new LoginUser();
        }
    }

    /**
     * 获取用户ID
     */
    public static Long getLoginUserId() {
        return getLoginUser().getUserId();
    }

    /**
     * 获取用户名
     */
    public static String getLoginUserName() {
        return getLoginUser().getUsername();
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

}
